{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 深度循环神经网络\n",
    "\n",
    ":label:`sec_deep_rnn`\n",
    "\n",
    "到目前为止，我们只讨论了具有一个单向隐藏层的循环神经网络。\n",
    "其中，隐变量和观测值与具体的函数形式的交互方式是相当随意的。\n",
    "只要交互类型建模具有足够的灵活性，这就不是一个大问题。\n",
    "然而，对于一个单层来说，这可能具有相当的挑战性。\n",
    "之前在线性模型中，我们通过添加更多的层来解决这个问题。\n",
    "而在循环神经网络中，我们首先需要确定如何添加更多的层，\n",
    "以及在哪里添加额外的非线性，因此这个问题有点棘手。\n",
    "\n",
    "事实上，我们可以将多层循环神经网络堆叠在一起，\n",
    "通过对几个简单层的组合，产生了一个灵活的机制。\n",
    "特别是，数据可能与不同层的堆叠有关。\n",
    "例如，我们可能希望保持有关金融市场状况\n",
    "（熊市或牛市）的宏观数据可用，\n",
    "而微观数据只记录较短期的时间动态。\n",
    "\n",
    " :numref:`fig_deep_rnn`描述了一个具有$L$个隐藏层的深度循环神经网络，\n",
    "每个隐状态都连续地传递到当前层的下一个时间步和下一层的当前时间步。\n",
    "\n",
    "![深度循环神经网络结构](https://d2l.ai/_images/deep-rnn.svg)\n",
    ":label:`fig_deep_rnn`\n",
    "\n",
    "## 函数依赖关系\n",
    "\n",
    "我们可以将深度架构中的函数依赖关系形式化，\n",
    "这个架构是由 :numref:`fig_deep_rnn`中描述了$L$个隐藏层构成。\n",
    "后续的讨论主要集中在经典的循环神经网络模型上，\n",
    "但是这些讨论也适应于其他序列模型。\n",
    "\n",
    "假设在时间步$t$有一个小批量的输入数据\n",
    "$\\mathbf{X}_t \\in \\mathbb{R}^{n \\times d}$\n",
    "（样本数：$n$，每个样本中的输入数：$d$）。\n",
    "同时，将$l^\\mathrm{th}$隐藏层（$l=1,\\ldots,L$）\n",
    "的隐状态设为$\\mathbf{H}_t^{(l)}  \\in \\mathbb{R}^{n \\times h}$\n",
    "（隐藏单元数：$h$），\n",
    "输出层变量设为$\\mathbf{O}_t \\in \\mathbb{R}^{n \\times q}$\n",
    "（输出数：$q$）。\n",
    "设置$\\mathbf{H}_t^{(0)} = \\mathbf{X}_t$，\n",
    "第$l$个隐藏层的隐状态使用激活函数$\\phi_l$，则：\n",
    "\n",
    "$$\\mathbf{H}_t^{(l)} = \\phi_l(\\mathbf{H}_t^{(l-1)} \\mathbf{W}_{xh}^{(l)} + \\mathbf{H}_{t-1}^{(l)} \\mathbf{W}_{hh}^{(l)}  + \\mathbf{b}_h^{(l)}),$$\n",
    ":eqlabel:`eq_deep_rnn_H`\n",
    "\n",
    "其中，权重$\\mathbf{W}_{xh}^{(l)} \\in \\mathbb{R}^{h \\times h}$，\n",
    "$\\mathbf{W}_{hh}^{(l)} \\in \\mathbb{R}^{h \\times h}$和\n",
    "偏置$\\mathbf{b}_h^{(l)} \\in \\mathbb{R}^{1 \\times h}$\n",
    "都是第$l$个隐藏层的模型参数。\n",
    "\n",
    "最后，输出层的计算仅基于第$l$个隐藏层最终的隐状态：\n",
    "\n",
    "$$\\mathbf{O}_t = \\mathbf{H}_t^{(L)} \\mathbf{W}_{hq} + \\mathbf{b}_q,$$\n",
    "\n",
    "其中，权重$\\mathbf{W}_{hq} \\in \\mathbb{R}^{h \\times q}$和偏置$\\mathbf{b}_q \\in \\mathbb{R}^{1 \\times q}$都是输出层的模型参数。\n",
    "\n",
    "与多层感知机一样，隐藏层数目$L$和隐藏单元数目$h$都是超参数。\n",
    "也就是说，它们可以由我们调整的。\n",
    "另外，用门控循环单元或长短期记忆网络的隐状态\n",
    "来代替 :eqref:`eq_deep_rnn_H`中的隐状态进行计算，\n",
    "可以很容易地得到深度门控循环神经网络或深度长短期记忆神经网络。\n",
    "\n",
    "## 简洁实现\n",
    "\n",
    "实现多层循环神经网络所需的许多逻辑细节在高级API中都是现成的。\n",
    "简单起见，我们仅示范使用此类内置函数的实现方式。\n",
    "以长短期记忆网络模型为例，\n",
    "该代码与之前在 :numref:`sec_lstm`中使用的代码非常相似，\n",
    "实际上唯一的区别是我们指定了层的数量，\n",
    "而不是使用单一层这个默认值。\n",
    "像往常一样，我们从加载数据集开始。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java\n",
    "%load ../utils/PlotUtils.java\n",
    "\n",
    "%load ../utils/StopWatch.java\n",
    "%load ../utils/Accumulator.java\n",
    "%load ../utils/Animator.java\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/timemachine/Vocab.java\n",
    "%load ../utils/timemachine/RNNModel.java\n",
    "%load ../utils/timemachine/RNNModelScratch.java\n",
    "%load ../utils/timemachine/TimeMachine.java\n",
    "%load ../utils/timemachine/TimeMachineDataset.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 32;\n",
    "int numSteps = 35;\n",
    "\n",
    "TimeMachineDataset dataset = new TimeMachineDataset.Builder()\n",
    "        .setManager(manager)\n",
    "        .setMaxTokens(10000)\n",
    "        .setSampling(batchSize, false)\n",
    "        .setSteps(numSteps)\n",
    "        .build();\n",
    "dataset.prepare();\n",
    "Vocab vocab = dataset.getVocab();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "像选择超参数这类架构决策也跟 :numref:`sec_lstm`中的决策非常相似。\n",
    "因为我们有不同的词元，所以输入和输出都选择相同数量，即`vocabSize`。\n",
    "隐藏单元的数量仍然是$256$。\n",
    "唯一的区别是，我们现在通过`setNumLayers()`的值来设定隐藏层数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int vocabSize = vocab.length();\n",
    "int numHiddens = 256;\n",
    "int numLayers = 2;\n",
    "Device device = manager.getDevice();\n",
    "LSTM lstmLayer =\n",
    "        LSTM.builder()\n",
    "                .setNumLayers(numLayers)\n",
    "                .setStateSize(numHiddens)\n",
    "                .optReturnState(true)\n",
    "                .optBatchFirst(false)\n",
    "                .build();\n",
    "\n",
    "RNNModel model = new RNNModel(lstmLayer, vocabSize);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## [**训练**]与预测\n",
    "\n",
    "由于使用了长短期记忆网络模型来实例化两个层，因此训练速度被大大降低了。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 500);\n",
    "\n",
    "int lr = 2;\n",
    "TimeMachine.trainCh8(model, dataset, vocab, lr, numEpochs, device, false, manager);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 在深度循环神经网络中，隐状态的信息被传递到当前层的下一时间步和下一层的当前时间步。\n",
    "* 有许多不同风格的深度循环神经网络，\n",
    "  如长短期记忆网络、门控循环单元、或经典循环神经网络。\n",
    "  这些模型在深度学习框架的高级API中都有涵盖。\n",
    "* 总体而言，深度循环神经网络需要大量的调参（如学习率和修剪）\n",
    "  来确保合适的收敛，模型的初始化也需要谨慎。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 基于我们在 :numref:`sec_rnn_scratch`中讨论的单层实现，\n",
    "   尝试从零开始实现两层循环神经网络。\n",
    "1. 在本节训练模型中，比较使用门控循环单元替换长短期记忆网络后模型的精确度和训练速度。\n",
    "1. 如果增加训练数据，你能够将困惑度降到多低？\n",
    "1. 在为文本建模时，是否可以将不同作者的源数据合并？有何优劣呢？\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
